// 存储已上传图片
let uploadedImages = [];

// 初始化上传功能
export function initUpload() {
    const imageUploadArea = document.getElementById('imageUploadArea');
    const imageInput = document.getElementById('imageInput');
    const previewContainer = document.getElementById('previewContainer');
    const previewImages = document.getElementById('previewImages');
    const imageCount = document.getElementById('imageCount');
    const generatePathBtn = document.getElementById('generatePathBtn');

    // 点击上传区域触发文件选择
    imageUploadArea.addEventListener('click', () => imageInput.click());

    // 处理文件选择
    imageInput.addEventListener('change', (e) => {
        if (!e.target.files.length) return;
        previewImages.innerHTML = '';
        uploadedImages = [];

        Array.from(e.target.files).forEach((file, index) => {
            const reader = new FileReader();
            reader.onload = (event) => {
                const imageData = { id: Date.now() + index, src: event.target.result, file };
                uploadedImages.push(imageData);
                renderPreview(imageData, previewImages); // 渲染预览图
                updateUploadStatus(imageCount, previewContainer, generatePathBtn); // 更新状态
            };
            reader.readAsDataURL(file);
        });
    });

    // 删除图片
    previewImages.addEventListener('click', (e) => {
        const removeBtn = e.target.closest('.remove-image');
        if (!removeBtn) return;
        const imageId = parseInt(removeBtn.getAttribute('data-id'));
        uploadedImages = uploadedImages.filter(img => img.id !== imageId);
        removeBtn.parentElement.remove();
        updateUploadStatus(imageCount, previewContainer, generatePathBtn);
    });
}

// 渲染图片预览
function renderPreview(imageData, container) {
    const previewEl = document.createElement('div');
    previewEl.className = 'preview-image-container';
    previewEl.innerHTML = `
        <img src="${imageData.src}" class="preview-image" alt="预览图片">
        <div class="remove-image" data-id="${imageData.id}">
            <i class="fa fa-times text-xs text-neutral-600"></i>
        </div>
    `;
    container.appendChild(previewEl);
}

// 更新上传状态（按钮启用/预览显示）
function updateUploadStatus(countEl, container, btn) {
    countEl.textContent = uploadedImages.length;
    if (uploadedImages.length > 0) {
        container.classList.remove('hidden');
        btn.disabled = false;
    } else {
        container.classList.add('hidden');
        btn.disabled = true;
    }
}

// 获取已上传图片（供其他模块调用）
export function getUploadedImages() {
    return uploadedImages;
}